import { useState, useEffect, useCallback } from 'react'
import { Flex, WhiteSpace, Card } from 'antd-mobile'
import { Button, message } from 'antd'
import router from 'umi/router'

import services from '@/services'
import { mapQuery } from '@/utils'
import styles from './index.scss'

const { SBTbranchs, SBQueue } = services

export default () => {
  const openId = localStorage.getItem('openId')
  const itemId = Number(mapQuery().itemId) // 上一页选择的事项
  const [options, setOptions] = useState([])

  const onBranchClick = useCallback((branchId,longitude, latitude) => {
    const data = {
      openId,
      longitude,
      itemId,
      branchId,
      latitude
    }
    SBQueue({
      sign: `${JSON.stringify(data)}$$##1234ech**`.MD5(32),
      data: data
    })
    .then(res => {
      if(res.success) {
        message.success(res.data, 1, () => {
          router.push('/result?type=take')
        })
      } else {
        message.warning(res.data)
      }
    })

  }, [])

  useEffect(() => {
    const data = {
      openId,
      itemId
    }
    SBTbranchs({
      sign: `${JSON.stringify(data)}$$##1234ech**`.MD5(32),
      data
    })
      .then(res => {
        console.log('网点列表', res)
        if (res.success) {
          setOptions(res.data)
        }
      })
  }, [])

  return (
    <div>
      <div>您的附近有多个网点，请选择需要前往的网点：</div>
      {
        options.map(i => (
          <div key={i.branchId}>
            <WhiteSpace />
            <Card className={styles.card}>
              <Flex justify='between' align='center' style={{ minHeight: 80 }}>
                <div>
                  <div>网点名称：{i.name}</div>
                  <div>地址：{i.address}</div>
                </div>
                <div>
                  <Button type='primary' onClick={() => onBranchClick(i.branchId, i.longitude, i.latitude)}>选择</Button>
                </div>
              </Flex>
            </Card>
          </div>
        ))
      }
    </div>
  )
}
